App({
  globalData: {
    // Mock sensor data with historical values for tracking
    sensorData: {
      current: {
        // 阈值变量(可设置)
        CO2threshold: 800,      // 等效二氧化碳浓度阈值, 初始值800
        Tvocthreshold: 500,     // 有机挥发物浓度阈值, 初始值500  
        MQthreshol: 1000,       // MQ-2阈值, 初始值1000
        
        // 传感器数据变量(只读)
        analogValue: 0,     // MQ-2原始值
        boomswitch: 0,          // 报警开关
        Z: 0,                 // Z轴加速度(g)
        Y: 0,                // Y轴加速度(g)
        X: 0,                 // X轴加速度(g)
        Speed: 0,               // 速度(km/h)
        Longitude: 0,    // 经度
        Latitude: 0,      // 纬度(北京天安门起始位置)
        co2: 0,             // 等效二氧化碳浓度(ppm)
        Tvoc: 0,            // 有机挥发物浓度(ppb)
        GasConcentration: 0, // 气体浓度(%)
        Humidity: 0,         // 湿度(%RH)
        Temperature: 0      // 温度(℃)
      },
      // 历史记录
      history: []
    },

    mqttClient: null,
    mqttConnected: false,
    
    // 页面数据回调列表
    pageDataCallbacks: {},
    pageConnectionCallbacks: {}
  },
  

  
  onLaunch: function() {
    console.log('App Launch');
    this.initializeSensorData();
    this.initializeMQTT();
  },

  // 初始化传感器数据
  initializeSensorData: function() {
    const now = Date.now();
    const currentData = this.globalData.sensorData.current;
    
    // 初始化历史记录
    this.globalData.sensorData.history = [{
      ...currentData,
      timestamp: now
    }];
    
    console.log('Sensor data initialized');
  },



  initializeMQTT: function() {
    try {
      const mqtt = require('./utils/mqtt.js');
      this.globalData.mqttClient = mqtt;
      
      // 设置连接状态回调
      mqtt.setConnectionCallback((connected) => {
        console.log('MQTT连接状态:', connected);
        this.globalData.mqttConnected = connected;
        if (connected) {
          this.startDataUpload();
        }
        
        // 分发连接状态到所有已注册的页面
        this.distributeConnectionStatusToPages(connected);
      });

      // 设置数据接收回调
      mqtt.setDataCallback((data) => {
        console.log('收到MQTT数据:', data);
        // 更新全局传感器数据
        Object.keys(data).forEach(key => {
          if (this.globalData.sensorData.current.hasOwnProperty(key)) {
            this.globalData.sensorData.current[key] = data[key];
          }
        });
        
        // 分发数据到所有已注册的页面
        this.distributeDataToPages(data);
      });

      // 连接MQTT
      mqtt.connect()
        .then(() => {
          console.log('阿里云IoT连接成功');
        })
        .catch((error) => {
          console.error('阿里云IoT连接失败:', error);
        });
    } catch (error) {
      console.error('MQTT初始化失败:', error);
    }
  },

  startDataUpload: function() {
    if (this.dataUploadTimer) {
      clearInterval(this.dataUploadTimer);
    }
    
    this.dataUploadTimer = setInterval(() => {
      if (this.globalData.mqttConnected && this.globalData.mqttClient) {
        this.globalData.mqttClient.sendData(
          this.globalData.sensorData.current
        ).catch(error => {
          console.log('数据上传失败:', error);
        });
      }
    }, 5000);
  },

  // 更新传感器数据（供页面调用）
  updateSensorData: function(data) {
    console.log('App层更新传感器数据:', data);
    
    // 更新全局数据
    Object.keys(data).forEach(key => {
      if (this.globalData.sensorData.current.hasOwnProperty(key)) {
        this.globalData.sensorData.current[key] = data[key];
      }
    });
    
    // 通过MQTT发送到云端
    if (this.globalData.mqttConnected && this.globalData.mqttClient) {
      return this.globalData.mqttClient.sendData(data);
    }
    return Promise.reject('MQTT未连接');
  },

  onHide: function() {
    console.log('App隐藏');
    if (this.dataUploadTimer) {
      clearInterval(this.dataUploadTimer);
    }
    // 在后台时保持连接，但可以降低重连频率
  },

  onShow: function() {
    console.log('App显示');
    // 恢复自动重连
    if (this.globalData.mqttClient) {
      this.globalData.mqttClient.enableAutoReconnect();
    }
    
    if (this.globalData.mqttConnected) {
      this.startDataUpload();
    } else if (this.globalData.mqttClient) {
      // 如果未连接，尝试重新连接
      this.globalData.mqttClient.connect().catch(error => {
        console.log('重连失败:', error);
      });
    }
  },

  // 注册页面数据回调
  registerPageDataCallback: function(pageId, callback) {
    console.log('注册页面数据回调:', pageId);
    this.globalData.pageDataCallbacks[pageId] = callback;
  },

  // 注册页面连接状态回调
  registerPageConnectionCallback: function(pageId, callback) {
    console.log('注册页面连接状态回调:', pageId);
    this.globalData.pageConnectionCallbacks[pageId] = callback;
  },

  // 注销页面回调
  unregisterPageCallbacks: function(pageId) {
    console.log('注销页面回调:', pageId);
    delete this.globalData.pageDataCallbacks[pageId];
    delete this.globalData.pageConnectionCallbacks[pageId];
  },

  // 分发数据到所有页面
  distributeDataToPages: function(data) {
    Object.keys(this.globalData.pageDataCallbacks).forEach(pageId => {
      try {
        const callback = this.globalData.pageDataCallbacks[pageId];
        if (typeof callback === 'function') {
          callback(data);
        }
      } catch (error) {
        console.error(`页面 ${pageId} 数据回调错误:`, error);
      }
    });
  },

  // 分发连接状态到所有页面
  distributeConnectionStatusToPages: function(connected) {
    Object.keys(this.globalData.pageConnectionCallbacks).forEach(pageId => {
      try {
        const callback = this.globalData.pageConnectionCallbacks[pageId];
        if (typeof callback === 'function') {
          callback(connected);
        }
      } catch (error) {
        console.error(`页面 ${pageId} 连接状态回调错误:`, error);
      }
    });
  }
})
